define(["jquery","base", "aes", "sha512"],function(jq){
	console.log("ajax utils initialze ... ...");
  

  jq.prepareUrl = function(url, param) {
    var res = url;
    if (!window.debug || !url) {
      return res;
    }
    var idx = -1;
    if ((idx = url.indexOf("/fn")) >= 0) {
      res = url.substring(0, idx) + "/data/debug/fn"
          + url.substr(idx + 3);
      if (param) {
        var param_txt = JSON.stringify(param).replace(/\:/g, "=")
            .replace(/\{/g, "").replace(/\}/g, "").replace(/\"/g,
                "").replace(/\'/g, "").replace(/\,/g, "_");
        if (param_txt.length > 0) {
          res += "_" + param_txt;
        }
      }
      res += ".json"
    }
    console.log("prepare url:\"" + url + "\" to \"" + res + "\"");
    return res;
  };


  jq.a = (function() {

    /**
     * Ajax工具类.
     * 
     * @constructor .
     */
    function AjaxUtils() {
    }

    (function() {
      var JsonFormatter = {
        stringify : function(cipherParams) {
          // create json object with ciphertext
          var jsonObj = {
            ct : cipherParams.ciphertext.toString(CryptoJS.enc.Hex)
          };
          // optionally add iv and salt
          if (cipherParams.iv) {
            jsonObj.iv = cipherParams.iv.toString();
          }
          if (cipherParams.salt) {
            jsonObj.s = cipherParams.salt.toString();
          }

          // stringify json object
          return JSON.stringify(jsonObj);
        },
        parse : function(jsonStr) {
          // parse json string
          var jsonObj = JSON.parse(jsonStr);
          // extract ciphertext from json object, and create cipher
          // params object
          var cipherParams = CryptoJS.lib.CipherParams.create({
            ciphertext : CryptoJS.enc.Hex.parse(jsonObj.ct)
          });
          // optionally extract iv and salt
          if (jsonObj.iv) {
            cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv)
          }
          if (jsonObj.s) {
            cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s)
          }
          return cipherParams;
        }
      };

      var pwd = '31323334353637383132333435363738';
      var x = pwd;
      pwd = CryptoJS.enc.Hex.parse(pwd);
      var y = pwd;
      var iv = pwd;// CryptoJS.enc.Hex.parse('31323334353637383132333435363738');
      window.encrypt = {
        iv : iv,
        // mode:CryptoJS.mode.CBC,
        // padding:CryptoJS.pad.Pkcs7,
        format : JsonFormatter
      };
    })();

    /**
     * ajax请求默认值.
     */
    AjaxUtils.DEFAULTS = {
      type : "POST",
      crossDomain : true,
      accepts : "application/*",
      contentType : "application/json",
      dataType : "json",
      success :  function(data, textStatus, jqXHR){},
      error : function(jqXHR, textStatus, errorThrown) {
        console.log("error", jqXHR+" [status:" + textStatus + "] " + errorThrown);
      },
      async : true,
      data : "{}",
      url : '#'
    };
    
    /**
     * 同步请求.
     * 
     * @param options
     *          请求选项.
     * @returns 当用户指定了success方法时无返回值；当success方法没有返回时，如果请求成功返回服务器端返回数据解析后的对象.
     */
    AjaxUtils.sync = function(options) {
      console.log(JSON.stringify(options))
      var settings = jq.extend({}, AjaxUtils.DEFAULTS, options, {
        async : false
      });
      if (settings.success === jQuery.noop) {
        var res = undefined;
        settings.success = function(data) {
          res = data;
        };
        
        jq.ajax(settings);
        return res;
      } else {
        return jq.ajax(settings);
      }
    };

    /**
     * 异步请求.
     * 
     * @param options
     *          请求选项.
     * @returns 无返回值.
     */
    AjaxUtils.async = function(options) {
      return jq.ajax(jq.extend({}, AjaxUtils.DEFAULTS, options, {
        async : true
      }));
    };

    /**
     * 加载脚本.
     * 
     * @param options
     *          请求选项.
     * @returns 无返回值.
     */
    AjaxUtils.loadScript = function(options) {
      return AjaxUtils.sync(jq.extend({}, options, {
        dataType : 'script'
      }));
    };

    var AJAX_UTILS = new AjaxUtils();

    var interfaceFunc = function(options, url, parameter,
        callbackOnSuccess, callbackOnFailure) {
      /*
       * 当输入参数为一个对象时,代理jQuery.ajax()方法.
       */
      if (typeof options == 'object') {
        return jq.ajax(options);
      }
      var method = undefined;
      if (typeof options == 'string') {
        method = jq.a.METHODS[options];
      } else {
        return undefined;
      }

      var args = {};
      if (callbackOnFailure) {
        args.error = callbackOnFailure;
      }
      if (callbackOnSuccess) {
        args.success = callbackOnSuccess;
      }
      if (parameter) {

        args.data = JSON.stringify(parameter);
        //console.log("encrypt:"+JSON.stringify(window.encrypt))
        if (window.encrypt) {
          var mi = CryptoJS.AES.encrypt(args.data, window.encrypt.iv, {
            format : window.encrypt.format,
            iv : window.encrypt.iv
          });
          mi = JSON.parse(mi.toString());
          args.data = mi.ct;
          args.dataFilter = function(data, type) {
            var msg = CryptoJS.enc.Hex.parse(data);
            msg = CryptoJS.enc.Base64.stringify(msg);
            var decrypted = CryptoJS.AES.decrypt(msg,
                window.encrypt.iv, {
                  iv : window.encrypt.iv
                });
            return (CryptoJS.enc.Utf8.stringify(decrypted).toString());
          }
        }

      }
      if (url) {
        args.url = url;
      }
      return method.call(AJAX_UTILS, args);
    };

    interfaceFunc.METHODS = {
      "sync" : function() {
        return AjaxUtils.sync.apply({}, arguments);
      },
      "async" : function() {
        return AjaxUtils.async.apply({}, arguments);
      },
      "loadScript" : function() {
        return AjaxUtils.loadScript.apply({}, arguments);
      },
      "postJson" : function(setting) {

        var defaultSetting = {
          type : "POST",
          accepts : "text/*",
          contentType : "application/json",
          dataType : "json"
        };
        return AjaxUtils.sync.call({}, jq.extend({}, defaultSetting,
            setting));
      },
      "getJson" : function(setting) {
        var defaultSetting = {
          type : "get",
          accepts : "text/*",
          contentType : "application/json",
          dataType : "json"
        };

        return AjaxUtils.sync.call({}, jq.extend({}, defaultSetting,
            setting));
      },
      "postJsonA" : function(setting) {
        var defaultSetting = {
          type : "POST",
          accepts : "text/*",
          contentType : "application/json",
          dataType : "json"
        };

        return AjaxUtils.async.call({}, jq.extend({}, defaultSetting,
            setting));
      }
    };
    return interfaceFunc;
  })();
  
});